#include <stdio.h>
#include <windows.h>
#include <process.h>

#include "sys_types.h"
#include "term_win32.h"

#include "lvgl.h"
#include "lv_port_disp.h"
#include "lv_port_indev.h"

/*****************************************************************************/

extern void desktop_start(void);
extern void desktop_refresh(void);

int event_gui_done;
int is_gui_running;
static void gui_proc(void* p)
{
	(void)p;

	desktop_start();

	for (;;) {
		lv_task_handler();
		Sleep(10);
		desktop_refresh();
		if (!is_gui_running) break;
	}
}

HANDLE th_gui_thread;

int gui_start()
{
	is_gui_running = 1;
	th_gui_thread = _beginthread(gui_proc, 0, 0);

	return 0;
}

int gui_done()
{
	is_gui_running = 0;
	WaitForSingleObject(th_gui_thread, INFINITE);
	return 0;
}

/*****************************************************************************/

unsigned char mouse_key;
signed short  mouse_delta_x_gui;
signed short  mouse_delta_y_gui;
signed char   mouse_wheel;

unsigned char* user_font_base;

int main(int argc, char* argv[])
{
	FILE* f;
	int run = 1;

	vo_create(RENDER_WIDTH, RENDER_HEIGHT, 1);

	user_font_base = 0;

	f = fopen("..\\..\\..\\..\\tools\\lv_font_zh_cn.bin", "rb");
	if (f) {
		int file_size;

		fseek(f, 0, SEEK_END);
		file_size = ftell(f);
		fseek(f, 0, SEEK_SET);

		user_font_base = malloc(file_size);
		if (user_font_base) {
			fread(user_font_base, file_size, 1, f);
		}

		fclose(f);
	}
	
	lv_init();
	lv_port_disp_init();
	lv_port_indev_init();

	gui_start();

	while (run) {
		MSG Msg;

		int r = ev_poll(&Msg);
		int key;

		if (WM_QUIT == r) {
			break;
		}

		switch (r) {
			case WM_NULL:
				Sleep(60);
				break;
			case WM_TIMER:
				break;
			case WM_PAINT:
				//vo_get_frame();
				//vo_set_frame();
				break;
		}

		key = key_scan();

		switch (key) {
			case VK_END:
//			case VK_ESCAPE:
				run = 0;
				break;

			case VK_SPACE:
				break;

			case 'S':
				break;

			case 'P':
				break;

			case VK_LEFT:
				break;
			case VK_RIGHT:
				break;
			case VK_UP:
				break;
			case VK_DOWN:
				break;
		}
	}

	gui_done();

	if (user_font_base)
		free(user_font_base);

	vo_destroy();

	return 0;
}

/*******************************************************************************
 *                               END OF FILE
 ******************************************************************************/
